#!/sbin/openrc-run
# Copyright 2017-2021 Hyperbola Project
# Distributed under the terms of the GNU General Public License v2

CHROOT=/srv/nginxchroot
PIDFILE=/var/run/nginx.pid
CONFFILE=/etc/nginx/nginx.conf
SVCNAME=nginx

extra_commands="checkconfig"
extra_started_commands="reload"
description="Robust, small and high performance http and reverse proxy server"
description_checkconfig="Run nginx' internal config check."
description_upgrade="Upgrade the nginx binary without losing connections."
description_reload="Reload the nginx configuration without losing connections."

depend() {
	use net dns logger netmount
}

checkconfig() {
        if [ ! -c ${CHROOT}/dev/random ] ; then
                mknod -m 666 ${CHROOT}/dev/null c 1 3
                mknod -m 644 ${CHROOT}/dev/random c 1 8
                mknod -m 644 ${CHROOT}/dev/urandom c 1 9
                mount -ro remount ${CHROOT}/dev
        fi

        checkpath --quiet --mode 755 --owner http:http --directory 'dirname ${CHROOT}${PIDFILE}'

        # now verify whether the configuration is valid
	/usr/sbin/${SVCNAME} -c ${CHROOT}${CONFFILE} -t -q

        if [ $? -eq 0 ] ; then
                einfo "Nginx configuration (${CHROOT}${CONFFILE}) is valid."
                return 0
        else
                eerror "Nginx configuration (${CHROOT}${CONFFILE}) not valid."
		/usr/sbin/${SVCNAME} -c ${CHROOT}${CONFFILE} -t	
                return 1
        fi
}

start() {
        checkconfig || return 1
        ebegin "Starting chrooted Nginx"
        # Detect old version and upgrade
        Nginxchroothash=$(sha256sum ${CHROOT}/usr/sbin/nginx | awk '{print $1}')
        Nginxoutsidehash=$(sha256sum /usr/sbin/nginx | awk '{print $1}')
        if [ "$Nginxchroothash" != "$Nginxoutsidehash" ]
        then
            	echo "New version of Tor detected! Updating chroot before running."
		    umount ${CHROOT}/tmp
		    umount ${CHROOT}/var/run
		    rm -rf ${CHROOT}
                wait
                /usr/bin/sh -c "/usr/libexec/nginx-hardened-scripts/nginxchroot.sh"
                wait
        fi
	start-stop-daemon --start --pidfile "${CHROOT}${PIDFILE}" --quiet --exec chroot -- --userspec=http:http ${CHROOT} /usr/sbin/${SVCNAME} -g 'pid /var/run/nginx.pid; daemon on; master_process on;' > /dev/null 2>&1
        eend $?
}

stop() {
        ebegin "Stopping chrooted Nginx"
        start-stop-daemon --stop --pidfile "${CHROOT}${PIDFILE}"
	rm -f "${CHROOT}${PIDFILE}"
        eend $?
}

reload() {
        if [ ! -f ${CHROOT}${PIDFILE} ]; then
                eerror "${SVCNAME} isn't running"
                return 1
        fi
        checkconfig || return 1
        ebegin "Reloading chrooted Nginx configuration"
        start-stop-daemon --signal HUP --pidfile ${CHROOT}${PIDFILE}
        eend $? "Failed to reload chrooted Nginx"
}
